'''
登录与注册数据持久化
'''
import os
import time
import json


def reg():
    print('------------注册--------------')
    username = input('username:')
    password = input('password:')
    new_user = []
    if username and password:
        with open('file/users.json', 'r') as rs:
            json_users = rs.read()
            users = json.loads(json_users)
        for user in users:
            if username == user[0]:
                print('账号已存在')
                return reg()
        else:
            new_user.append(username)
            new_user.append(password)
            users.append(new_user)
            with open('file/users.json', 'w') as ws:
                json_users = json.dumps(users)
                ws.write(json_users)
            print('注册成功，返回主页')
            time.sleep(0.5)
            return welcome()
    else:
        print('用户名和密码不能为空')
        return welcome()


# 登录
def login():
    print('-------------登录-------------------')
    while 1:
        username = input('username:')
        password = input('password:')
        with open('file/users.json', 'r') as rs:
            json_users = rs.read()
            users = json.loads(json_users)
        for user in users:
            if username == user[0]:
                if password == user[1]:
                    print('登录成功！')
                    print('正在加载主页面...')
                    time.sleep(1)
                    return welcome()
                else:
                    print('账号或密码输入有误，请重新登录！')
                    return welcome()
        else:
            print('账号不存在，请重新登录！')
            return welcome()


def welcome():
    print('---------------欢迎来到主页--------------------')
    print('1登录 2注册 3退出')
    while 1:
        num = input('请输入编号：')
        if num == '1':
            login()
        elif num == '2':
            reg()
        elif num == '3':
            exit()
        else:
            print('编码输入错误，请重新输入')


print('-------------欢迎进入**管理系统-----------------')
# 数据初始化
# os.mkdir('file')
# with open('file/users.json', 'w') as create_file:
#     first_data = json.dumps([])
#     create_file.write(first_data)
welcome()
